package com.member.common.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class AMapUtils {


    // 高德地图key
    public static final String KEY = "c9jAmfWjCUe3ZwKKMCdAuRgfhWbBEW2G";


    public static final String SHOW_LOCATION = "showLocation&&showLocation";
    public static final String STATUS = "status";

    public static double[] addressToGPS(String param) {
        //配置上自己的百度地图应用的AK
        String applicationId = "c9jAmfWjCUe3ZwKKMCdAuRgfhWbBEW2G";
        try {
            InputStream urlStream;
            String address = param.trim();
            URL url = new URL("https://api.map.baidu.com/geocoding/v3/?address=" + address + "&output=json&ak=" + KEY + "&callback=showLocation");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            urlStream = connection.getInputStream();
            java.io.BufferedReader reader = new java.io.BufferedReader(new InputStreamReader(urlStream));
            String str = reader.readLine();
            System.out.println(str);
            if (StringUtils.hasLength(str) && str.startsWith(SHOW_LOCATION)) {
                str = str.replaceAll("showLocation&&showLocation\\(", "");
                str = str.replaceAll("\\)", "");
            }
            JSONObject jsonObject = JSON.parseObject(str);
            if (jsonObject.getInteger(STATUS) != 0) {
                return null;
            }
            JSONObject location = (JSONObject) ((JSONObject) jsonObject.get("result")).get("location");
            //用经度分割返回的网页代码
            double[] gps = new double[2];
            Double lng = location.getDouble("lng");
            Double lat = location.getDouble("lat");
            gps[0] = lng;
            gps[1] = lat;
            return gps;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
